package com.offcn.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Data
public class OssTemplate {

    //oos服务器端点访问地址
    private String endpoint;
    //存储桶的访问域名
    private String bucketDomain;
    //秘钥1
    private String accessKeyId;
    //秘钥2
    private String accessKeySecret;
    //存储桶的名称
    private String bucketName;

    //使用oos进行上传方法
    public String upload(InputStream inputStream,String fileName){

        //按照日期时间创建文件夹
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String folderName  = dateFormat.format(new Date());
        //为了避免上传重名文件，造成文件丢失，为文件名增加一个随机数
      fileName=  UUID.randomUUID().toString().replace("-","")+"_"+fileName;

       //创建OSScLIENT
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //执行文件上传
        ossClient.putObject(bucketName,"pic/"+folderName+"/"+fileName,inputStream);

        //关闭流
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String url="http://"+bucketDomain+"/pic/"+folderName+"/"+fileName;

        System.out.println("文件上传访问地址:"+url);

        return url;
    }
}
